﻿//默认分页参数定义
paginationOptions={layout:['list','sep','first','prev','sep','manual','sep','next','last','sep','refresh'],
		pageSize:15,
		pageList:[15,30,50],
	    onSelectPage: onSelectPage
}
gridParam={"pageNumber":1,"pageSize":paginationOptions.pageSize};
/**
 * 当点击排序的时候触发
 * sort：排序的列的字段名
   order：排序的列的顺序
 */
function onSortColumn(sort, order){
	gridParam.sort=sort;
	gridParam.order=order;
	dg.datagrid("load");
}
function onDblClickRow(rowIndex,rowData){
	dg.datagrid('beginEditing',rowData);
}
/**
 * 当翻页时触发
 */
function onSelectPage(pageNumber, pageSize){
	gridParam.pageNumber=pageNumber;
	gridParam.pageSize=pageSize;
	dg.datagrid("load");
}
$.extend($.fn.validatebox.defaults.rules, {
		unique:{
	        validator: function(value,param){
	        	//console.log(param);
	        	var editId=dg.data('editId');
	        	if(editId==undefined){
	        		//setTimeout('',200);
	        		return true;
	        	}
	        	//var idField=dg.datagrid('options').idField;
	        	//var id= dg.datagrid('getRows')[dg.data('editIndex')].id;
	        	var check=$.ajax({
	        		type: "post",
	    			contentType:"application/json",
								async:false,
								url: "/authenticated/ajax/boolean/"+param[0],
								data:JSON.stringify({'username':value,'id':editId}),
								dataType:"json",
								success: function(result){
									return result;
								},
								error: function(){
									return false;
								}
							}).responseText;
	        	return check=='true';
	        },
	        message: '选项已存在,请重新录入.'
	    }
});
$.extend($.fn.textbox.methods, {
	addClearBtn: function(jq, iconCls){
		return jq.each(function(){
			var t = $(this);
			var opts = t.textbox('options');
			opts.icons = opts.icons || [];
			opts.icons.unshift({
				iconCls: iconCls,
				handler: function(e){
					$(e.data.target).textbox('clear').textbox('textbox').focus();
					$(this).css('visibility','hidden');
				}
			});
			t.textbox();
			if (!t.textbox('getText')){
				t.textbox('getIcon',0).css('visibility','hidden');
			}
			t.textbox('textbox').bind('keyup', function(){
				var icon = t.textbox('getIcon',0);
				if ($(this).val()){
					icon.css('visibility','visible');
				} else {
					icon.css('visibility','hidden');
				}
			});
		});
	}
});
//$('#tt').textbox().textbox('addClearBtn', 'icon-clear');
$.extend($.fn.datagrid.methods, {
	cancelEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		if (editId){
			var editIndex=dg.datagrid('getRowIndex',editId);
			if(editIndex){
				dg.datagrid('cancelEdit',editIndex);
			}
		}
	},
	beginEditing:function(jq,param){
		var dg=jq;
		var idField=dg.datagrid('options').idField;
		var rowid=param[idField];
		var rowIndex=dg.datagrid('getRowIndex',rowid);
		if(dg.data('editId')!=rowid){
    		if(dg.datagrid('endEditing')){
    			//开始编辑
    			dg.datagrid('beginEdit', rowIndex);
				dg.data('editId',rowid);
    		}
    	}
	},
	endEditing:function(jq){
		var dg=jq;
		var editId = dg.data('editId');
		if (editId == undefined){return true;}
		var editIndex=dg.datagrid('getRowIndex',editId);
		if (editIndex == undefined||editIndex<0){return true;}
		if (dg.datagrid('validateRow', editIndex)){
			dg.datagrid('endEdit', editIndex);
			dg.removeData('editId');
			return true;
		} else {
			return false;
		}
	},
	append:function(jq,param){
		return jq.each(function(){
			var dg=jq;
			if(dg.datagrid('endEditing')){
				var length=dg.datagrid('getRows').length;
				var idField=dg.datagrid('options').idField;
				dg.datagrid('appendRow',param);//新增一行
				dg.data('editId',param[idField]);
				dg.datagrid('selectRow', length).datagrid('beginEdit',length);//编辑新增行
			}
		});
	},
	editRow:function(jq,param){
		var dg=jq;
		var selectRows=dg.datagrid('getSelections');
		if(selectRows.length>0){
			dg.datagrid('beginEditing',selectRows[0]);
		}else{
			$.messager.alert("提示", "请选择一条数据！");
		}
	},
	remove:function(jq){
		var dg=jq;
		var selectRow=dg.datagrid('getSelections');
		if(selectRow.length>0){
			$.each(selectRow,function(i,v){
				var deleteIndex=dg.datagrid('getRowIndex',v);
				dg.datagrid('deleteRow', deleteIndex);
			});
		}
	},
	getEditIndex:function(jq){
		var dg=jq;
		var editIndex=undefined;
		var editId = dg.data('editId');
		if (editId){
			editIndex=dg.datagrid('getRowIndex',editId);
		}
		return editIndex;
	},
	load:function(jq,param){
		var dg=jq;
		dg.datagrid("loading");
		var searchbar=dg.datagrid('options').toolbar;
		var table=dg.datagrid('options').table;
		var sqlname=dg.datagrid('options').sqlname;
		if(!sqlname){
			sqlname="grid_"+table;
		}
		var searchForm=$(searchbar+" form");
		var searchParam=searchForm.serializeObject();
		$.extend(searchParam,gridParam);
		$.post("/authenticated/grid/"+sqlname,JSON.stringify(searchParam),function(result){
			dg.datagrid("loadData",result.rows);
			pager.pagination('refresh',{
				total: result.total,
				pageNumber: gridParam.pageNumber
			});
			dg.datagrid("loaded");
		});
		
	},accept:function(jq,param){
		var dg=jq;
		var table=dg.datagrid('options').table;
		var sqlname=dg.datagrid('options').sqlname;
		if(!sqlname){
			sqlname="grid_"+table;
		}
		if (dg.datagrid('endEditing')){
			var rows = dg.datagrid('getChanges');
			if (rows.length == 0) {
				$.messager.alert("提示", "没有需要提交的数据！");
				return;
			}
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows  = dg.datagrid('getChanges','deleted');
			var updatedRows  = dg.datagrid('getChanges','updated');
			var params = {};
			if(insertedRows.length>0){
				params.insertedRows=insertedRows;
			}
			if(updatedRows.length>0){
				params.updatedRows=updatedRows;
			}
			if(deletedRows.length>0){
				var idArr=new Array();
				var idField=dg.datagrid('options').idField;
				$.each(deletedRows, function(i, row){
					idArr.push(row[idField]);
				});
				params.deletedRowIds=idArr;
			}
			$.ajax({
				type: "post",
				contentType:"application/json",
				url: "/authenticated/grid/update/"+sqlname,
				data:JSON.stringify(params),
				success: function(result){
					if(result.success){
						dg.datagrid('acceptChanges');
						dg.datagrid('load');
						$.messager.alert("提示", "保存成功！");
					}else{
						$.messager.alert("错误", result.message);
					}			
				}
			});
		}
	},showChanges:function(jq,param){
		var dg=jq;
		if (dg.datagrid('endEditing')){
			var changesRows=dg.datagrid('getChanges');
			var insertedRows = dg.datagrid('getChanges','inserted');
			var deletedRows = dg.datagrid('getChanges','deleted');
			var updatedRows = dg.datagrid('getChanges','updated');
			$.messager.alert("提示", changesRows.length+"条数据修改<br>新增"+insertedRows.length+"条,删除"+deletedRows.length+"条，更新"+updatedRows.length+"条");
		}else{
			$.messager.alert("提示", "编辑未结束！");
		}
	},getSelectedRow:function(jq,param){
		var dg=jq;
		var selectRow=dg.datagrid('getSelected');
		if(selectRow){
			return selectRow;
		}else{
			$.messager.alert("提示", $.messager.defaults.selectRow);
			return undefined;
		}
	}
});
